<!-- <attachment>
<file:daping/daping/src/components/Butterfly.vue> -->
<template>
  <div
    class="butterfly"
    :class="clicked ? 'butterfly-clicked' : ''"
    @animationend="end"
    @click="flyAway"
  >
    <img :src="clicked ?flyImage:butterflyImage" class="butterImage" style="transform:rotate(90deg)" alt="Butterfly" />
  </div>
</template>

<script setup>
import butterflyImage from "../assets/butterfly.svg";
import flyImage from "../assets/fly.svg";
import {calculateAngle,createCssRule} from "../utils/buttly.js"; 
import { ref, onMounted } from "vue";
const clicked = ref(false);
const randomX = ref(0);
const randomY = ref(0);
const oldX = ref(0);
const oldY = ref(0);
let butterfly = null;
let img = null;
const rotate = ref(0);

const flyAway = () => {
  clicked.value = true;
  init()
  if (randomX.value - oldX.value < 100 && randomY.value - oldY.value < 50) {
    // 如果新位置与旧位置太近，则重新生成
    randomX.value += 200;
    randomY.value += 50;
  }
  createCssRule(randomX, randomY, oldX, oldY); // 创建CSS规则
  img.style.transform = `rotate(${calculateAngle(randomX,randomY,oldX,oldY)}deg)`; // 设置旋转角度
};


onMounted(() => {
  butterfly = document.querySelector(".butterfly");
  img = document.querySelector(".butterImage");
  img.style.transform = `rotate(180deg)`; // 设置初始旋转角度
  // 初始化随机位置
  init();
  save(); // 保存初始位置
  butterfly.style.transform = `translate(${randomX.value}px, ${randomY.value}px)`; // 设置初始位置

});
const init = () => {
  randomX.value = Math.random() * 500; // 随机生成X轴偏移
  randomY.value = Math.random() * 200; // 随机生成Y轴偏移
};
const save = () => {
  console.log("Saving current position:", randomX.value, randomY.value);
  oldX.value = randomX.value; // 保存当前的随机位置
  oldY.value = randomY.value; // 保存当前的随机位置
};
const end = (dom) => {
  clicked.value = false;
  save(); // 保存当前的位置
  butterfly.style.transform = `translate(${randomX.value}px, ${randomY.value}px)`; // 隐藏蝴蝶元素
};
</script>

<style scoped>
.butterfly {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px; /* Adjust size as needed */
  height: auto;
  cursor: pointer;
  /* transition: transform 0.5s; */
}
.butterfly-clicked {
  animation: flyAway linear 3s forwards;
}
.butterfly img {
  width: 100%; /* Adjust size as needed */
  height: auto;
}

</style>
<!-- </attachment> -->
